package mythread;

/**
 * @Auther: cty
 * @Date: 2020/1/8 11:17
 * @Description:  死锁——过多同步可能造成相互不释放资源，从而相互等待，一般发生于同步中持有多个对象的锁
 * 避免：不要在一段代码块中同时获取多个锁
 * @version: 1.0
 */
public class Hi_DeadLock {
    public static void main(String[] args) {
        Markup g1 = new Markup(0,"大丫");
        Markup g2 = new Markup(1,"小丫");
        g1.start();
        g2.start();
    }
}

//口红
class Lipstick{

}

//镜子
class Mirror{

}

//化妆
class Markup extends Thread{
    //化妆用品
    private static Lipstick lipstick = new Lipstick();
    private static Mirror  mirror = new Mirror();
    //选择
    private int choice;
    //女孩姓名
    private String girl;

    public Markup(int choice, String girl){
        this.choice = choice;
        this.girl = girl;
    }

    @Override
    public void run() {
        //化妆
        markup();
    }

    private void markup(){
        if(choice == 0){
            synchronized(lipstick){
                System.out.println(this.girl+"涂口红");
            // 1秒后想拥有镜子的锁
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
//                synchronized(mirror){
//                    System.out.println(this.girl+"照镜子");
//                }
            }
            synchronized(mirror){
                System.out.println(this.girl+"照镜子");
            }
        }else{
            synchronized(mirror){
                System.out.println(this.girl+"照镜子");

                // 2秒后想拥有口红的锁
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
//                synchronized(lipstick){
//                    System.out.println(this.girl+"涂口红");
//                }
            }
            synchronized(lipstick){
                System.out.println(this.girl+"涂口红");
            }
        }
    }
}
